package org.ece3574.WTParty;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.Facebook.ServiceListener;
import com.facebook.android.FacebookError;

public class WTPFacebook implements DialogListener, ServiceListener{
	
	private static final String FB_APP_ID = "308821595837030";
	
	private Facebook facebook;
	private Activity context;
	private SharedPreferences mPrefs;
	private LoginListener loginListener;
	
	public WTPFacebook(Activity context)
	{
		this.context = context;
		facebook = new Facebook(FB_APP_ID);
		mPrefs = context.getSharedPreferences("WTParty", Activity.MODE_PRIVATE);
	}
	
	/*
	 * Facebook login
	 */
	public boolean isLoggedIn()
	{
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        if(access_token != null) {
            facebook.setAccessToken(access_token);
            facebook.setAccessExpires(expires);
            if(facebook.isSessionValid())
            {
            	facebook.extendAccessTokenIfNeeded(context, this);
            	return true;
            }
        }
        return false;
	}
	
	public void login(Activity myActivity, LoginListener listener)
	{
		loginListener = listener;
		facebook.authorize(myActivity, this);
		
	}

	public void handleCallback(int requestCode, int resultCode, Intent data)
	{
		facebook.authorizeCallback(requestCode, resultCode, data);
	}
	
	public void onComplete(Bundle values) {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putString("access_token", facebook.getAccessToken());
        editor.putLong("access_expires", facebook.getAccessExpires());
        editor.commit();
		loginListener.loginSuccessful();
	}
	
	/* 
	 * the friends list on the user's Facebook profile is pulled and placed
	 * into an array on the friends tab of the app.	 
	 */
	public String[] getFriendList()
	{
		String[] friendList;
		try
		{
			String strFriends = facebook.request("me/friends");
			JSONArray jaFriendList = new JSONObject(strFriends).getJSONArray("data");
			friendList = new String[jaFriendList.length()];
			for(int i=0;i<jaFriendList.length();i++)
			{				
				friendList[i]=jaFriendList.getJSONObject(i).getString("name");
			}
		}
		catch(Exception e)
		{
			Log.d("Error", "Error getting friend list", e);
			return null;
		}
		Arrays.sort(friendList);
		return friendList;
	}
	
	public facebookProfile getProfile()
	{
		facebookProfile userProfile = new facebookProfile();
		try
		{
			String rawUserInfo = facebook.request("me");
			JSONObject jsonUserInfo = new JSONObject(rawUserInfo);
			userProfile.name = jsonUserInfo.getString("name");
			if(jsonUserInfo.has("hometown"))
					userProfile.hometown = jsonUserInfo.getJSONObject("hometown").getString("name");
			
			/*String strEvents = facebook.request("me/events");
			JSONArray jaEventList = new JSONObject(strEvents).getJSONArray("data");
			userProfile.events = jsonUserInfo.getJSONObject("events").getJSONArray("data");*/

			
			final String fbBaseURL = "https://graph.facebook.com/";
			String imageURL = fbBaseURL + "me/picture?type=large&access_token=" + facebook.getAccessToken();
			
			userProfile.picture = getImageBitmap(imageURL);
		}
		catch(Exception e)
		{
			Log.d("Error", "Error getting facebook profile", e);
			return null;
		}
		return userProfile;
	}
	
    private Bitmap getImageBitmap(String url) { 
        Bitmap bm = null; 
        try { 
            URL aURL = new URL(url); 
            URLConnection conn = aURL.openConnection(); 
            conn.connect(); 
            InputStream is = conn.getInputStream(); 
            BufferedInputStream bis = new BufferedInputStream(is); 
            bm = BitmapFactory.decodeStream(bis); 
            bis.close(); 
            is.close(); 
       } catch (IOException e) { 
    	   Log.e("Error", "Error getting image", e);
       } 
       return bm; 
    } 
	
	
	public void onFacebookError(FacebookError e) {
		// TODO Auto-generated method stub
		
	}

	public void onError(DialogError e) {
		// TODO Auto-generated method stub
		
	}

	public void onCancel() {
		// TODO Auto-generated method stub
		
	}

	public void onError(Error e) {
		// TODO Auto-generated method stub
		
	}

}


